package com.dzk.cp.c11x5.catcher.task;

import java.util.Date;

import javax.servlet.ServletContext;

import org.apache.log4j.Logger;
import org.springframework.web.context.ServletContextAware;

import com.dzk.cp.c11x5.pojo.R5;
import com.dzk.cp.util.CpUtils;
import com.dzk.cp.util.DateUtils;

public abstract class CodeCatcherTask<T extends R5> implements ServletContextAware {
	
	private static final Logger log = Logger.getLogger(CodeCatcherTask.class);
	
	private ServletContext servletContext;
	
	public void catchCode() {
		Object isLoaded = servletContext.getAttribute("isLoaded");
		if (isLoaded == null || Boolean.FALSE.equals(isLoaded)) {
			log.info("历史数据未加载完成，延迟执行.");
			return;
		}
		doCatchCode();
	}
	
	protected abstract void doCatchCode();
	
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}
	
	protected String getCurrentIssue(String saleTimeFrom, int frequency) {
		Long currSeconds = CpUtils.getServerCurrentTimeSeconds();
		String currDate = DateUtils.dateToStr(new Date(), "yyyyMMdd");
		String fromTime = currDate + " " + saleTimeFrom;
		Long fromSeconds = DateUtils.strToDate(fromTime, "yyyyMMdd HH:mm").getTime() / 1000;
		int n = (int) ((currSeconds - fromSeconds) / (frequency * 60));
		if (n < 1) {
			n = 1;
		}
		return currDate + CpUtils.fore2zero(n);
	}
	
	protected String getIssues(String fromIssue, String toIssue) {
		int a = Integer.valueOf(fromIssue);
		int b = Integer.valueOf(toIssue);
		String issues = "";
		for (int i = a; i <= b; i++) {
			issues += i + ",";
		}
		if (issues.length() > 0) {
			issues = issues.substring(0, issues.length() - 1);
		}
		return issues;
	}

}
